package cn.lili.modules.wallet.serviceimpl;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.properties.RocketmqCustomProperties;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.common.utils.SnowFlake;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.dos.RechargeFow;
import cn.lili.modules.member.service.RechargeFowService;
import cn.lili.modules.order.order.entity.dos.Order;
import cn.lili.modules.order.order.mapper.OrderMapper;
import cn.lili.modules.order.order.service.OrderService;
import cn.lili.modules.store.entity.vos.StoreDetailVO;
import cn.lili.modules.store.service.StoreDetailService;
import cn.lili.modules.system.service.RegionService;
import cn.lili.modules.transfer.entity.vo.TransferVO;
import cn.lili.modules.wallet.entity.dos.MemberWallet;
import cn.lili.modules.wallet.entity.dos.MemberWithdrawApply;
import cn.lili.modules.wallet.entity.dos.MemberWithdrawItem;
import cn.lili.modules.wallet.entity.dto.MemberWithdrawalMessage;
import cn.lili.modules.wallet.entity.enums.MemberWithdrawalDestinationEnum;
import cn.lili.modules.wallet.entity.enums.WalletOwnerEnum;
import cn.lili.modules.wallet.entity.enums.WithdrawStatusEnum;
import cn.lili.modules.wallet.entity.vo.MemberSalesWithdrawVO;
import cn.lili.modules.wallet.entity.vo.MemberWithdrawApplyQueryVO;
import cn.lili.modules.wallet.entity.vo.MemberWithdrawApplyVO;
import cn.lili.modules.wallet.mapper.MemberWithdrawApplyMapper;
import cn.lili.modules.wallet.service.MemberWalletService;
import cn.lili.modules.wallet.service.MemberWithdrawApplyService;
import cn.lili.modules.wallet.service.MemberWithdrawItemService;
import cn.lili.mybatis.util.PageUtil;
import cn.lili.rocketmq.RocketmqSendCallbackBuilder;
import cn.lili.rocketmq.tags.MemberTagsEnum;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 会员提现申请业务层实现
 *
 * @author pikachu
 * @since 2020-02-25 14:10:16
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MemberWithdrawApplyServiceImpl extends ServiceImpl<MemberWithdrawApplyMapper, MemberWithdrawApply>
		implements
			MemberWithdrawApplyService {

	@Autowired
	private RocketMQTemplate rocketMQTemplate;
	@Autowired
	private RocketmqCustomProperties rocketmqCustomProperties;

	@Autowired
	private StoreDetailService storeDetailService;

	@Autowired
	private OrderMapper orderMapper;

	@Autowired
	private OrderService orderService;
	/**
	 * 会员余额
	 */
	@Autowired
	private MemberWalletService memberWalletService;

	@Autowired
	private RechargeFowService rechargeFowService;

	@Autowired
	private MemberWithdrawItemService memberWalletItemService;

	@Autowired
	private RegionService regionService;

	@Override
	public Boolean audit(String applyId, String result, String remark) {
		MemberWithdrawalMessage memberWithdrawalMessage = new MemberWithdrawalMessage();
		// 查询申请记录
		MemberWithdrawApply memberWithdrawApply = this.getById(applyId);
		memberWithdrawApply.setInspectRemark(remark);
		memberWithdrawApply.setInspectTime(new Date());
		if (memberWithdrawApply != null) {
			// 获取账户余额
			// MemberWalletVO memberWalletVO =
			// memberWalletService.getMemberWallet(memberWithdrawApply.getMemberId(),
			// memberWithdrawApply.getOwner());
			// 校验金额是否满足提现，因为是从冻结金额扣减，所以校验的是冻结金额
			// if (memberWalletVO.getMemberFrozenWallet() <
			// memberWithdrawApply.getApplyMoney()) {
			// throw new
			// ServiceException(ResultCode.WALLET_WITHDRAWAL_FROZEN_AMOUNT_INSUFFICIENT);
			// }
			// 如果审核通过 则微信直接提现，反之则记录审核状态
			if (WithdrawStatusEnum.VIA_AUDITING.name().equals(result)) {
				memberWithdrawApply.setApplyStatus(WithdrawStatusEnum.VIA_AUDITING.name());
				// 提现，微信提现成功后扣减冻结金额
				Boolean bool = memberWalletService.withdrawal(memberWithdrawApply);
				if (bool) {
					memberWithdrawalMessage.setStatus(WithdrawStatusEnum.VIA_AUDITING.name());
					// 保存修改审核记录
					this.updateById(memberWithdrawApply);
					// 记录日志
					// memberWalletService.reduceFrozen(
					// new MemberWalletUpdateDTO(memberWithdrawApply.getApplyMoney(),
					// memberWithdrawApply.getMemberId(),
					// "审核通过，余额提现", DepositServiceTypeEnum.WALLET_WITHDRAWAL.name(),
					// memberWithdrawApply.getOwner()))
					// ;
				} else {
					// 如果提现失败则无法审核
					throw new ServiceException(ResultCode.WALLET_APPLY_ERROR);
				}
			} else if (WithdrawStatusEnum.FAIL_AUDITING.name().equals(result)) {
				memberWithdrawalMessage.setStatus(WithdrawStatusEnum.FAIL_AUDITING.name());
				// 如果审核拒绝 审核备注必填
				if (StringUtils.isEmpty(remark)) {
					throw new ServiceException(ResultCode.WALLET_REMARK_ERROR);
				}
				memberWithdrawApply.setApplyStatus(WithdrawStatusEnum.FAIL_AUDITING.name());
				// 保存修改审核记录
				this.updateById(memberWithdrawApply);
				String rem = "";
				switch (memberWithdrawApply.getOwner()) {
					case "STORE_PROMOTE" : {
						rem = "推广钱包";
						break;
					}
					case "BUYER_PROMOTE" : {
						rem = "推广钱包";
						break;
					}
					case "BUYER_PROMOTE_HY" : {
						rem = "推广钱包";
						break;
					}
					case "BUYER_PROMOTE_FW" : {
						rem = "推广钱包";
						break;
					}
					case "STORE_SALE" : {
						rem = "销售钱包";
						break;
					}
					case "PROMOTE" : {
						rem = "推广钱包";
						break;
					}
					case "PROMOTE_HY" : {
						rem = "推广钱包";
						break;
					}
					case "PROMOTE_FW" : {
						rem = "推广钱包";
						break;
					}
					case "SALE" : {
						rem = "销售钱包";
						break;
					}
					default :
						break;
				}
				String owner = memberWithdrawApply.getOwner();
				if (memberWithdrawApply.getOwner().indexOf("STORE") != -1) {
					owner = memberWithdrawApply.getOwner().substring(6, memberWithdrawApply.getOwner().length());
				} else if (memberWithdrawApply.getOwner().indexOf("BUYER") != -1) {
					owner = memberWithdrawApply.getOwner().substring(6, memberWithdrawApply.getOwner().length());
				}
				MemberWallet to = memberWalletService.getMemberWalletInfo(memberWithdrawApply.getMemberId(), owner);
				MemberWallet admin = memberWalletService.getMemberWalletInfo("admin", "RECHARGE", "平台");// 平台消费钱包
				memberWalletService.withdrawApplyRefund(memberWithdrawApply.getSn(), admin, to,
						memberWithdrawApply.getApplyPrice(), rem + "余额提现退回，拒绝原因：" + remark);

				// 推广钱包-会员费 提现
				if (owner.equals(WalletOwnerEnum.PROMOTE_HY.name())) {
					rechargeFowService.updatePromoteRefund(memberWithdrawApply.getSn(),
							memberWithdrawApply.getApplyPrice(), memberWithdrawApply.getMemberId(), "21");
				}
				// 销售钱包 提现
				if (owner.equals(WalletOwnerEnum.SALE.name())) {
					memberWalletItemService.updateSaleRefund(memberWithdrawApply.getSn(),
							memberWithdrawApply.getApplyPrice(), memberWithdrawApply.getMemberId(), "11");
				}

			} else if (WithdrawStatusEnum.CANCEL.name().equals(result)) {
				memberWithdrawalMessage.setStatus(WithdrawStatusEnum.CANCEL.name());
				memberWithdrawApply.setApplyStatus(WithdrawStatusEnum.CANCEL.name());
				// 保存修改撤销记录
				this.updateById(memberWithdrawApply);
				String rem = "";
				switch (memberWithdrawApply.getOwner()) {
					case "STORE_PROMOTE" : {
						rem = "推广钱包";
						break;
					}
					case "BUYER_PROMOTE" : {
						rem = "推广钱包";
						break;
					}
					case "BUYER_PROMOTE_HY" : {
						rem = "推广钱包";
						break;
					}
					case "BUYER_PROMOTE_FW" : {
						rem = "推广钱包";
						break;
					}
					case "STORE_SALE" : {
						rem = "销售钱包";
						break;
					}
					case "PROMOTE" : {
						rem = "推广钱包";
						break;
					}
					case "PROMOTE_HY" : {
						rem = "推广钱包";
						break;
					}
					case "PROMOTE_FW" : {
						rem = "推广钱包";
						break;
					}
					case "SALE" : {
						rem = "销售钱包";
						break;
					}
					default :
						break;
				}
				String owner = memberWithdrawApply.getOwner();
				if (memberWithdrawApply.getOwner().indexOf("STORE") != -1) {
					owner = memberWithdrawApply.getOwner().substring(6, memberWithdrawApply.getOwner().length());
				} else if (memberWithdrawApply.getOwner().indexOf("BUYER") != -1) {
					owner = memberWithdrawApply.getOwner().substring(6, memberWithdrawApply.getOwner().length());
				}
				MemberWallet to = memberWalletService.getMemberWalletInfo(memberWithdrawApply.getMemberId(), owner);
				MemberWallet admin = memberWalletService.getMemberWalletInfo("admin", "RECHARGE", "平台");// 平台消费钱包
				memberWalletService.withdrawApplyRefund(memberWithdrawApply.getSn(), admin, to,
						memberWithdrawApply.getApplyPrice(), rem + "余额提现撤销");

				// 推广钱包-会员费 提现
				if (owner.equals(WalletOwnerEnum.PROMOTE_HY.name())) {
					rechargeFowService.updatePromoteRefund(memberWithdrawApply.getSn(),
							memberWithdrawApply.getApplyPrice(), memberWithdrawApply.getMemberId(), "21");
				}
				// 销售钱包 提现
				if (owner.equals(WalletOwnerEnum.SALE.name())) {
					memberWalletItemService.updateSaleRefund(memberWithdrawApply.getSn(),
							memberWithdrawApply.getApplyPrice(), memberWithdrawApply.getMemberId(), "11");
				}

			}
			// 发送审核消息
			memberWithdrawalMessage.setMemberId(memberWithdrawApply.getMemberId());
			memberWithdrawalMessage.setPrice(memberWithdrawApply.getApplyPrice());
			memberWithdrawalMessage.setDestination(MemberWithdrawalDestinationEnum.WECHAT.name());

			String destination = rocketmqCustomProperties.getMemberTopic() + ":"
					+ MemberTagsEnum.MEMBER_WITHDRAWAL.name();
			rocketMQTemplate.asyncSend(destination, memberWithdrawalMessage,
					RocketmqSendCallbackBuilder.commonCallback());
			return true;
		}
		throw new ServiceException(ResultCode.WALLET_APPLY_ERROR);
	}

	@Override
	public IPage<MemberWithdrawApplyVO> getMemberWithdrawPage(PageVO pageVO,
			MemberWithdrawApplyQueryVO memberWithdrawApplyQueryVO) {
		// 构建查询条件
		QueryWrapper<MemberWithdrawApply> queryWrapper = new QueryWrapper<>();
		// 会员名称
		queryWrapper.like(!StringUtils.isEmpty(memberWithdrawApplyQueryVO.getMemberName()), "apply.member_name",
				memberWithdrawApplyQueryVO.getMemberName());
		// 充值订单号
		queryWrapper.eq(!StringUtils.isEmpty(memberWithdrawApplyQueryVO.getSn()), "apply.sn",
				memberWithdrawApplyQueryVO.getSn());
		// 会员id
		queryWrapper.eq(!StringUtils.isEmpty(memberWithdrawApplyQueryVO.getMemberId()), "apply.member_id",
				memberWithdrawApplyQueryVO.getMemberId());
		// 已付款的充值订单
		queryWrapper.eq(!StringUtils.isEmpty(memberWithdrawApplyQueryVO.getApplyStatus()), "apply.apply_status",
				memberWithdrawApplyQueryVO.getApplyStatus());
		// 开始时间和结束时间
		if (!StringUtils.isEmpty(memberWithdrawApplyQueryVO.getStartDate())
				&& !StringUtils.isEmpty(memberWithdrawApplyQueryVO.getEndDate())) {
			Date start = cn.hutool.core.date.DateUtil.parse(memberWithdrawApplyQueryVO.getStartDate());
			Date end = cn.hutool.core.date.DateUtil.parse(memberWithdrawApplyQueryVO.getEndDate());
			queryWrapper.between("apply.create_time", start, end);
		}
		// 订单来源
		queryWrapper.likeLeft(!StringUtils.isEmpty(memberWithdrawApplyQueryVO.getOwner()), "apply.owner",
				memberWithdrawApplyQueryVO.getOwner());
		queryWrapper.likeLeft(!StringUtils.isEmpty(memberWithdrawApplyQueryVO.getWalletType()), "apply.owner",
				memberWithdrawApplyQueryVO.getWalletType());
		queryWrapper.like(!StringUtils.isEmpty(memberWithdrawApplyQueryVO.getMobile()), "member.mobile",
				memberWithdrawApplyQueryVO.getMobile());
		queryWrapper.eq("apply.delete_flag", 0);
		// queryWrapper.eq("apply.apply_status", "VIA_AUDITING");
		queryWrapper.orderByDesc("apply.create_time");

		// 查询返回数据
		return this.baseMapper.getMemberWithdrawPage(PageUtil.initPage(pageVO), queryWrapper);
	}

	@Override
	public IPage<MemberWithdrawApplyVO> getList(PageVO pageVO, MemberWithdrawApplyQueryVO memberWithdrawApplyQueryVO) {
		// 构建查询条件
		QueryWrapper<MemberWithdrawApply> queryWrapper = new QueryWrapper<>();
		// 会员id
		queryWrapper.eq(!StringUtils.isEmpty(memberWithdrawApplyQueryVO.getMemberId()), "apply.member_id",
				memberWithdrawApplyQueryVO.getMemberId());
		// 开始时间和结束时间
		if (!StringUtils.isEmpty(memberWithdrawApplyQueryVO.getStartDate())
				&& !StringUtils.isEmpty(memberWithdrawApplyQueryVO.getEndDate())) {
			queryWrapper.le("DATE_FORMAT(apply.create_time,'%Y-%m-%d')", memberWithdrawApplyQueryVO.getEndDate());
			queryWrapper.ge("DATE_FORMAT(apply.create_time,'%Y-%m-%d')", memberWithdrawApplyQueryVO.getStartDate());
		}
		// 订单来源
		queryWrapper.likeLeft(!StringUtils.isEmpty(memberWithdrawApplyQueryVO.getOwner()), "apply.owner",
				memberWithdrawApplyQueryVO.getOwner());
		queryWrapper.eq("apply.delete_flag", 0);
		queryWrapper.orderByDesc("apply.create_time");

		// 查询返回数据
		return this.baseMapper.getMemberWithdrawPage(PageUtil.initPage(pageVO), queryWrapper);
	}

	@Override
	public IPage<MemberWithdrawApplyVO> getListPage(PageVO pageVO, QueryWrapper<MemberWithdrawApply> queryWrapper) {
		// 查询返回数据
		IPage<MemberWithdrawApplyVO> saleList = this.baseMapper.getSaleList(PageUtil.initPage(pageVO), queryWrapper);
		if (CollectionUtils.isNotEmpty(saleList.getRecords())) {
			for (MemberWithdrawApplyVO memberWithdrawApply : saleList.getRecords()) {
				if (StringUtils.isNotEmpty(memberWithdrawApply.getRegionId())) {
					memberWithdrawApply.setRegion(
							regionService.getItemAdCodOrName(StringUtils.toString(memberWithdrawApply.getRegionId())));
				}
				memberWithdrawApply.setFee(
						BigDecimal.valueOf(memberWithdrawApply.getFee() != null ? memberWithdrawApply.getFee() : 0D)
								.setScale(2, RoundingMode.DOWN).doubleValue());
				memberWithdrawApply.setApplyMoney(BigDecimal
						.valueOf(memberWithdrawApply.getApplyMoney() != null ? memberWithdrawApply.getApplyMoney() : 0D)
						.setScale(2, RoundingMode.DOWN).doubleValue());
				memberWithdrawApply.setApplyPrice(BigDecimal
						.valueOf(memberWithdrawApply.getApplyPrice() != null ? memberWithdrawApply.getApplyPrice() : 0D)
						.setScale(2, RoundingMode.DOWN).doubleValue());
				memberWithdrawApply.setRealMoney(BigDecimal
						.valueOf(memberWithdrawApply.getRealMoney() != null ? memberWithdrawApply.getRealMoney() : 0D)
						.setScale(2, RoundingMode.DOWN).doubleValue());
				memberWithdrawApply
						.setWithholdingAdvance(BigDecimal.valueOf(memberWithdrawApply.getWithholdingAdvance() != null
								? memberWithdrawApply.getWithholdingAdvance()
								: 0D).setScale(2, RoundingMode.DOWN).doubleValue());
			}
		}
		return saleList;
	}

	@Override
	public List<MemberWithdrawApplyVO> getListAll(QueryWrapper<MemberWithdrawApply> queryWrapper) {
		// 查询返回数据
		List<MemberWithdrawApplyVO> saleList = this.baseMapper.getListAll(queryWrapper);
		if (CollectionUtils.isNotEmpty(saleList)) {
			for (MemberWithdrawApplyVO memberWithdrawApply : saleList) {
				if (StringUtils.isNotEmpty(memberWithdrawApply.getRegionId())) {
					memberWithdrawApply.setRegion(
							regionService.getItemAdCodOrName(StringUtils.toString(memberWithdrawApply.getRegionId())));
				}
				memberWithdrawApply.setApplyMoney(BigDecimal
						.valueOf(memberWithdrawApply.getApplyMoney() != null ? memberWithdrawApply.getApplyMoney() : 0D)
						.setScale(2, RoundingMode.DOWN).doubleValue());
				memberWithdrawApply.setApplyPrice(BigDecimal
						.valueOf(memberWithdrawApply.getApplyPrice() != null ? memberWithdrawApply.getApplyPrice() : 0D)
						.setScale(2, RoundingMode.DOWN).doubleValue());
				memberWithdrawApply.setRealMoney(BigDecimal
						.valueOf(memberWithdrawApply.getRealMoney() != null ? memberWithdrawApply.getRealMoney() : 0D)
						.setScale(2, RoundingMode.DOWN).doubleValue());
				memberWithdrawApply
						.setWithholdingAdvance(BigDecimal.valueOf(memberWithdrawApply.getWithholdingAdvance() != null
								? memberWithdrawApply.getWithholdingAdvance()
								: 0D).setScale(2, RoundingMode.DOWN).doubleValue());
			}
		}
		return saleList;
	}

	// 获取当前人店铺提现金额
	@Override
	public IPage<MemberSalesWithdrawVO> getdeposit(PageVO pageVO, MemberSalesWithdrawVO memberWithdrawApplyQueryVO) {
		// String id = UserContext.getCurrentUser().getId();
		StoreDetailVO storeDetailVOByMemberId = storeDetailService
				.getStoreDetailVOByMemberId(memberWithdrawApplyQueryVO.getId());
		QueryWrapper<MemberSalesWithdrawVO> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("store_id", storeDetailVOByMemberId.getStoreId());
		queryWrapper.orderByAsc("fee");
		return this.baseMapper.getdeposit(PageUtil.initPage(pageVO), queryWrapper);
	}

	@Override
	public void batchUpdate(String status, String id, Double surplus, Double surplusPrice) {
		this.baseMapper.batchUpdate(status, id, surplus, surplusPrice);
	}

	@Override
	public List<MemberSalesWithdrawVO> getFeesum(String id) {
		if(id == null) {
			id = UserContext.getCurrentUser().getId();
		}
		StoreDetailVO storeDetailVOByMemberId = storeDetailService.getStoreDetailVOByMemberId(id);
		return this.baseMapper.getFeesum(storeDetailVOByMemberId.getStoreId());
	}

	@Override
	public List<MemberWithdrawApply> getList(String ids) {
		return this.baseMapper.getList(ids);
	}

	@Override
	public boolean save(List<MemberWithdrawApply> messages) {
		return this.save(messages);
	}

	@Override
	public Integer UpdateApplyStaytus(String status, String idArr) {
		return this.baseMapper.UpdateApplyStaytus(status, idArr);
	}

	@Override
	public List<MemberWithdrawApply> queryList() {
		String id = UserContext.getCurrentUser().getId();
		Member member = orderMapper.getMemberInfo(id);
		return this.baseMapper.queryList(member.getId());
	}

	@Override
	public IPage<MemberWithdrawApply> queryWithdrawApplyList(PageVO pageVO,
			QueryWrapper<MemberWithdrawApply> queryWrapper) {
		IPage<MemberWithdrawApply> memberWithdrawApplyIPage = this.baseMapper.queryLists(PageUtil.initPage(pageVO),
				queryWrapper);
		return memberWithdrawApplyIPage;
	}

	@Override
	public List<MemberWithdrawApply> queryMemberWithdrawApplyList(String memberId) {
		String id = UserContext.getCurrentUser().getId();
		// String id ="1534437963574001666";
		Member member = orderMapper.getMemberInfo(id);
		return this.baseMapper.queryList(member.getId());
	}

	@Override
	public Map<String, Object> txList(Double totalMoney, String sn, String id, String type) {
		Map<String, Object> map = new HashMap<>();
		Double allPrice = totalMoney;
		// List<MemberSalesWithdrawVO> list = new ArrayList();
		List<MemberSalesWithdrawVO> search = this.getFeesum(id);
		// BigDecimal flowprice = BigDecimal.valueOf(0);// 焕呗总额
		// BigDecimal surplus = BigDecimal.valueOf(0);// 剩余可提现额度
		// for (MemberSalesWithdrawVO item : search) {
		// flowprice = flowprice.add(BigDecimal.valueOf(item.getFlowprice()));
		// surplus = surplus.add(BigDecimal.valueOf(item.getSurplus()));
		// item.setFlowpriceSum(flowprice);
		// item.setSurplusSum(surplus);
		// BigDecimal divide = surplus.divide(flowprice, 5, BigDecimal.ROUND_DOWN);
		// item.setFeeSum(divide.doubleValue());
		// list.add(item);
		// }
		Double alreadyMoney = 0D;// 已扣除现金
		Double alreadyPrice = 0D;// 已扣除焕呗
		if (CollectionUtils.isNotEmpty(search)) {
			for (MemberSalesWithdrawVO item : search) {
				// 循环出每一次的记录
				if (totalMoney.compareTo(item.getSurplusPrice()) >= 0) {
					// 应扣除焕呗额大于等于可扣除焕呗额，把整条记录都扣完
					alreadyMoney = CurrencyUtil.add(alreadyMoney, item.getSurplus());// 增加已扣除现金
					alreadyPrice = CurrencyUtil.add(alreadyPrice, item.getSurplusPrice());// 增加已扣除焕呗
					totalMoney = CurrencyUtil.sub(totalMoney, item.getSurplusPrice());// 应扣除焕呗额减少
					// 插入数据到明细表
					MemberWithdrawItem memberWithdrawItem = new MemberWithdrawItem();
					memberWithdrawItem.setApplyMoney(item.getSurplusPrice());
					memberWithdrawItem.setRealMoney(item.getSurplus());
					memberWithdrawItem.setOrderItemId(item.getId());
					memberWithdrawItem.setSn(sn);
					memberWithdrawItem.setMemberId(id);
					memberWithdrawItem.setFee(item.getFee());
					memberWithdrawItem.setType(type);
					memberWithdrawItem.setCreateTime(new Date());
					memberWalletItemService.save(memberWithdrawItem);
					// 修改已经提现完的订单
					batchUpdate("-1", item.getId(), 0D, 0D);
				} else {
					// 应扣除焕呗额小于可扣除焕呗额，只扣除一部分
					Double canMoney = CurrencyUtil.mul(totalMoney, item.getFee());// 扣除现金 = 应扣除焕呗额 * 费率

					alreadyMoney = CurrencyUtil.add(alreadyMoney, canMoney);// 增加已扣除现金
					alreadyPrice = CurrencyUtil.add(alreadyPrice, totalMoney);// 增加已扣除焕呗

					// 插入数据到明细表
					MemberWithdrawItem memberWithdrawItem = new MemberWithdrawItem();
					memberWithdrawItem.setApplyMoney(totalMoney);// 扣除焕呗
					memberWithdrawItem.setRealMoney(canMoney);// 扣除现金
					memberWithdrawItem.setOrderItemId(item.getId());
					memberWithdrawItem.setSn(sn);
					memberWithdrawItem.setMemberId(id);
					memberWithdrawItem.setFee(item.getFee());
					memberWithdrawItem.setType(type);
					memberWalletItemService.save(memberWithdrawItem);

					// 修改充值明细表信息
					Double price1 = CurrencyUtil.sub(item.getSurplus(), canMoney);// 剩余现金 = 可扣除现金 - 扣除现金
					Double price2 = CurrencyUtil.sub(item.getSurplusPrice(), totalMoney);// 剩余焕呗额 = 可扣除焕呗额 - 扣除焕呗额
					// 修改订单
					batchUpdate("0", item.getId(), price1, price2);
					totalMoney = 0D;
					break;
				}
			}
		}
//		map.put("alreadyPrice", alreadyPrice);
		map.put("alreadyPrice", allPrice);
		map.put("alreadyMoney", alreadyMoney);
		map.put("fee", CurrencyUtil.div(alreadyMoney, allPrice));
		map.put("colPrice", CurrencyUtil.sub(allPrice, alreadyMoney));// 手续费
		return map;

	}

	@Override
	public IPage<MemberWithdrawItem> queryItemLists(PageVO pageVO, QueryWrapper<MemberWithdrawItem> queryWrapper) {
		return this.baseMapper.queryItemLists(PageUtil.initPage(pageVO), queryWrapper);
	}

	@Override
	public Long saleNum() {
		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.eq("apply_status", "APPLY");
		queryWrapper.like("owner", "STORE");
		queryWrapper.eq("delete_flag", false);
		return this.count(queryWrapper);
	}

	@Override
	public Long promoteNum() {
		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.eq("apply_status", "APPLY");
		queryWrapper.like("owner", "BUYER");
		queryWrapper.eq("delete_flag", false);
		return this.count(queryWrapper);
	}

	public List<MemberSalesWithdrawVO> search(List<MemberSalesWithdrawVO> logsList) {
		Collections.sort(logsList, new Comparator<MemberSalesWithdrawVO>() {
			@Override
			public int compare(MemberSalesWithdrawVO o1, MemberSalesWithdrawVO o2) {
				if ((o1.getFee() > o2.getFee())) {
					return 1;
				}
				if (o1.getFee() == o2.getFee()) {
					return 0;
				}
				return -1;
			}
		});
		return logsList;
	}

	public List<MemberSalesWithdrawVO> searchs(List<MemberSalesWithdrawVO> logsList) {
		Collections.sort(logsList, new Comparator<MemberSalesWithdrawVO>() {
			@Override
			public int compare(MemberSalesWithdrawVO o1, MemberSalesWithdrawVO o2) {
				if ((o1.getFee() > o2.getFee())) {
					return -1;
				}
				if (o1.getFee() == o2.getFee()) {
					return 0;
				}
				return 1;
			}
		});
		return logsList;
	}
}